﻿using System;
using Autodesk.Revit.DB;
using QuickModel.QuickModelFrame;

namespace QuickModel.Demo
{
	[Rebuilder(RebuilderName = "test")]
	public class UseRebuilder : IRevitModelRebuilder
	{
		public bool TryRebuildRevitModel(Autodesk.Revit.DB.Document inputDoc, RevitModelRequest inputReqeust, out BuildData createdElement)
		{
			createdElement = new BuildData();
			bool result;
			try
			{
				UseRevitModelRequest useRevitModelRequest = inputReqeust as UseRevitModelRequest;
				LineElement lineElement = inputReqeust.RequestData.LstCurveElements[0] as LineElement;
				LineElement lineElement2 = inputReqeust.RequestData.LstCurveElements[1] as LineElement;
				bool flag = lineElement.ThisCurve.Project(lineElement2.ThisCurve.GetEndPoint(0)).XYZPoint.IsAlmostEqualTo(lineElement.ThisCurve.GetEndPoint(0));
				XYZ xyz;
				XYZ xyz2;
				double num;
				if (flag)
				{
					xyz = (lineElement.ThisCurve.GetEndPoint(0) + lineElement2.ThisCurve.GetEndPoint(0)) / 2.0;
					xyz2 = (lineElement.ThisCurve.GetEndPoint(1) + lineElement2.ThisCurve.GetEndPoint(1)) / 2.0;
					num = lineElement.ThisCurve.GetEndPoint(0).DistanceTo(lineElement2.ThisCurve.GetEndPoint(0));
				}
				else
				{
					xyz = (lineElement.ThisCurve.GetEndPoint(0) + lineElement2.ThisCurve.GetEndPoint(1)) / 2.0;
					xyz2 = (lineElement.ThisCurve.GetEndPoint(1) + lineElement2.ThisCurve.GetEndPoint(0)) / 2.0;
					num = lineElement.ThisCurve.GetEndPoint(0).DistanceTo(lineElement2.ThisCurve.GetEndPoint(1));
				}
				Line line = Line.CreateBound(xyz, xyz2);
				string useTypeName = inputReqeust.UseTypeName;
				FilteredElementCollector filteredElementCollector = new FilteredElementCollector(inputDoc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType();
				Autodesk.Revit.DB.ElementType elementType = null;
				foreach (Element element in filteredElementCollector.ToElements())
				{
					bool flag2 = element.Name == useTypeName;
					if (flag2)
					{
						elementType = (element as Autodesk.Revit.DB.ElementType);
						break;
					}
				}
				Transaction transaction = new Transaction(inputDoc, "creatWall");
				transaction.Start();
				elementType = elementType.Duplicate(useTypeName + Guid.NewGuid().ToString());
				CompoundStructure compoundStructure = (elementType as WallType).GetCompoundStructure();
				compoundStructure.SetLayerWidth(0, num);
				(elementType as WallType).SetCompoundStructure(compoundStructure);
				createdElement.CreatedElement = Wall.Create(inputDoc, line, (inputDoc.ActiveView as ViewPlan).GenLevel.Id, false);
				(createdElement.CreatedElement as Wall).WallType = (elementType as WallType);
				transaction.Commit();
				result = true;
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}
	}
}
